//
//  ChonZhiViewController.m
//  YDD
//
//  Created by 欧洪飞 on 2017/8/22.
//  Copyright © 2017年 jy. All rights reserved.
//

#import "ChonZhiViewController.h"
#import "PayTypeTableViewCell.h"
#import "PalyTypeModel.h"
#import "PaymentHelpClass.h"

#import "WXApi.h"
#import "Order.h"
#import "APAuthV2Info.h"
#import "RSADataSigner.h"
#import <AlipaySDK/AlipaySDK.h>

#import "BankCardViewController.h"
#import "PayCell.h"
#import "SelectPayCell.h"
@interface ChonZhiViewController ()<UITextFieldDelegate,UITableViewDataSource,UITableViewDelegate>{
    SelectPayCell *payCell;
    NSArray *array1;
    NSArray *array2;
    NSString *orderNum;//订单号
}
@property (weak, nonatomic) IBOutlet UIView *viewCard;
@property (weak, nonatomic) IBOutlet UIImageView *imageBank;
@property (weak, nonatomic) IBOutlet UILabel *labBank;
@property (weak, nonatomic) IBOutlet UILabel *labCard;
@property (weak, nonatomic) IBOutlet UITableView *playTypeTable;

@property (weak, nonatomic) IBOutlet UITextField *textPrice;
@property (weak, nonatomic) IBOutlet UILabel *labDZPrice;


//主要是用来接收用户上一次所选的cell的indexpath
@property (nonatomic,strong) NSIndexPath *lastPath;
@property (nonatomic,copy)NSString *payment;//支付方式

@end

@implementation ChonZhiViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self showNav:@"充值"];
    array1 = @[@"微信2",@"支付宝-(1)",@"钱包-(1)"];
    array2 = @[@"微信支付",@"支付宝支付",@"余额支付"];
    
    self.viewCard.hidden = YES;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(clickPayNote) name:@"PayResultNSNotification" object:nil];
    _textPrice.delegate = self;
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    //生产订单号
    [self loadData];
    
}

-(void)textFieldDidEndEditing:(UITextField *)textField{
    _labDZPrice.text = [NSString stringWithFormat:@"￥%.2f",textField.text];
    
}

//NSNotificationCenter
- (void)clickPayNote{
    NSLog(@"aaasdddd");
    [self payLoadData];
    
}

//用户充值余额
- (IBAction)clickCZ:(id)sender {
    if (self.textPrice.text.length == 0) {
        [LICGToast showWithText:@"请输入充值金额"];
        return;
    }else if (_payment.length == 0){
        [LICGToast showWithText:@"请选择充值方式"];
        return;
    }
    if ([_payment isEqualToString:@"2"]) {//微信支付
        [self loadWX];
    }else if ([_payment isEqualToString:@"3"]){//支付宝支付
        [self loadAliPay];
    }
    
}

//用户充值余额
- (void)payLoadData{
    NSString *str = [NSString stringWithFormat:@"%@890d69e502d1d37a9e84335ccefece57",[user objectForKey:@"token2"]];
    NSString *token = [LCMD5Tool md5:str];
    NSMutableDictionary *parmas = [NSMutableDictionary dictionary];
    [parmas setObject:token forKey:@"verifyToken"];
    [parmas setObject:[user objectForKey:@"userid"] forKey:@"userid"];
    [parmas setObject:_textPrice.text forKey:@"rechargeMoney"];
    if ([_payment isEqualToString:@"2"]) {//微信
        [parmas setObject:@"wechat" forKey:@"rechargeMode"];
    }else{
        [parmas setObject:@"alipay" forKey:@"rechargeMode"];
    }
    [parmas setObject:orderNum forKey:@"ordernumber"];
    NSString *url = [NSString stringWithFormat:@"%@/App/Usercenter/userRecharge",urlHead];
    [[AFHTTPSessionManager manager] POST:url parameters:parmas success:^(NSURLSessionDataTask *task, id responseObject) {
        NSLog(@"res:%@",responseObject);
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"error:%@",error);
    }];
    
}



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 2;
}
//行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 50;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 44;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *sectionView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 44)];
    [sectionView setBackgroundColor:[UIColor clearColor]];
    UIView *line = [[UIView alloc]initWithFrame:CGRectMake(0, 43, ScreenWidth, 1)];
    [line setBackgroundColor:HexColorInt32_t(D9D9D9)];
    [sectionView addSubview:line];
    UIView *lineShu = [[UIView alloc]initWithFrame:CGRectMake(12, 13.5, 4, 17)];
    [lineShu setBackgroundColor:HexColorInt32_t(4184FF)];
    [sectionView addSubview:lineShu];
    UILabel *sectionLabel = [[UILabel alloc]initWithFrame:CGRectMake(27, 14, ScreenWidth - 27, 16)];
    [sectionLabel setFont:[UIFont systemFontOfSize:16]];
    [sectionLabel setTextColor:HexColorInt32_t(313131)];
    [sectionLabel setText:@"选择支付方式"];
    [sectionView addSubview:sectionLabel];
    return sectionView;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellId = @"Cell";
    payCell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if (!payCell) {
        payCell = [[[NSBundle mainBundle] loadNibNamed:@"SelectPayCell" owner:nil options:nil] lastObject];
    }
    payCell.selectionStyle = UITableViewCellSelectionStyleNone;
    payCell.images.image = [UIImage imageNamed:array1[indexPath.row]];
    payCell.labTit.text = array2[indexPath.row];
    
    NSInteger row = indexPath.row;
    NSInteger oldRow = _lastPath.row;
    if (row == oldRow && _lastPath != nil) {
        payCell.imageSel.image = [UIImage imageNamed:@"勾"];
    }else{
        payCell.imageSel.image = [UIImage imageNamed:@"椭圆-2-拷贝"];
    }
    return payCell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *str = array2[indexPath.row];
    if ([str isEqualToString:@"微信支付"]) {
        _payment = @"2";
    }else if ([str isEqualToString:@"支付宝支付"]){
        _payment = @"3";
    }else if ([str isEqualToString:@"银联支付"]){
        _payment = @"4";
    }else{
        _payment = @"5";
    }
    
    NSInteger newrow = indexPath.row;
    NSInteger oldRow = (self.lastPath != nil)?self.lastPath.row:-1;
    if (newrow != oldRow) {
        payCell = [tableView cellForRowAtIndexPath:indexPath];
        payCell.imageSel.image = [UIImage imageNamed:@"勾"];
        
        payCell = [tableView cellForRowAtIndexPath:self.lastPath];
        payCell.imageSel.image = [UIImage imageNamed:@"椭圆-2-拷贝"];
        self.lastPath = indexPath;
        
    }
}


//微信
- (void)loadWX{
    NSMutableDictionary *parmas = [NSMutableDictionary dictionary];
    [parmas setObject:_textPrice.text forKey:@"total"];//死的价格
    [parmas setObject:orderNum forKey:@"ordernumber"];
    [parmas setObject:@"充值" forKey:@"subject"];
    [parmas setObject:@"充值" forKey:@"detail"];
    [parmas setObject:@"http://ydd.xtangguo.com/index.php/App/Blitzcrank/cleaningorderpay" forKey:@"notify_url"];
    NSString *url = [NSString stringWithFormat:@"%@/App/WxPay/dopay",urlHead];
    
    [[AFHTTPSessionManager manager] POST:url parameters:parmas success:^(NSURLSessionDataTask *task, id responseObject) {
        NSLog(@"res:%@",responseObject);
        NSDictionary *dic = responseObject;
        [self loadWXpay:dic];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"error:%@",error);
    }];
    
}

- (void)loadWXpay:(NSDictionary *)dic{
    //需要创建这个支付对象
    PayReq *req   = [[PayReq alloc] init];
    
    //由用户微信号和AppID组成的唯一标识，用于校验微信用户
    req.openID = [dic objectForKey:@"appid"];
    
    // 商家id，在注册的时候给的
    req.partnerId = [dic objectForKey:@"partnerid"];
    
    // 预支付订单这个是后台跟微信服务器交互后，微信服务器传给你们服务器的，你们服务器再传给你
    req.prepayId  = [dic objectForKey:@"prepayid"];
    
    // 根据财付通文档填写的数据和签名
    //这个比较特殊，是固定的，只能是即req.package = Sign=WXPay
    req.package   = [dic objectForKey:@"package"];
    
    // 随机编码，为了防止重复的，在后台生成
    req.nonceStr  = [dic objectForKey:@"noncestr"];
    
    // 这个是时间戳，也是在后台生成的，为了验证支付的
    NSString * stamp = [dic objectForKey:@"timestamp"];
    req.timeStamp = stamp.intValue;
    
    // 这个签名也是后台做的
    req.sign = [dic objectForKey:@"sign"];
    
    //发送请求到微信，等待微信返回onResp
    [WXApi sendReq:req];
}

//调用支付
- (void)loadAliPay{
    //2017041006619216
    NSString *appID = @"2017041006619216";//持有者ID
    //支付宝公钥
    NSString *rsa2PrivateKey = @"";//支付宝公钥 2048
    
    NSString *rsaPrivateKey = @"MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAIeaW3BL5JgblDIBDCec3JAfiWs88agOcQzUOXlVHncFAtFyJjsJLV2+DV32ASog2Wk5Dh+KcbefEg/dtHx/y8Tgt++zfm6eTo/KHwgka+SiGQNs8nvldeYwXu1nQ3xDhGfGBJL7F0PXBkALoJNQE6xVM5n/KeSzZfESYcPARXRlAgMBAAECgYAsrI7JXUdvUU6udqfheQ01Mh6cxNQ8cJ2QA2736TIDNhRqmje8JVbb1lwjA4P4tB/MSa68d2jlfLN/pKPsjFG+CxcFeSnpvnVBy27m4Eg7CAQ+8M+1bKluWu6hNXUSw5oLFEWOdTX5hOlU2XjHRo9t4H+LWUZPwN64qbrp68EuVQJBAN+TAg8zgVDE8yZZ+KuCCGHHq9vpiKw9207gJv+TSlnEstB2CgyZH/9w36ytk5g7u+85msmuGUaV+rg5m28G4NsCQQCbRRnXeU/UE5klSPy/jhXHCAUpQbGjoqWPbDSi+Ahb3211gftUJdJsQfFq2JK28iY0kHYfciGJ7VA7sJ8XPWO/AkBY+uYv7JzD646mLdq1T6xMVi6E+J4HhxrYeoeq4hEORyWvp7r6JptAi8jJrc93IBb879019U9j8170oSDGgGNPAkBn0qba6+UzG/+1bL6En890DKrW0XSkxGcMJgB0UIHWXOnmPwn9VGUFunphRXulFPny//3cPQasIaEaqJlYgtYlAkEAxwPw51+P2Wjcq0bc6377mWlMUtiQpORY/ABBsu8bbon/kweveCr4V952MAWNLHQqSPZrtBVO1y1RND64+8UwTA==";//1024
    //partner和seller获取失败,提示
    if ([appID length] == 0 ||
        ([rsa2PrivateKey length] == 0 && [rsaPrivateKey length] == 0))
    {
        NSLog(@"appid/ras不能为空");
        return;
    }
    
    /*
     *生成订单信息及签名
     */
    //将商品信息赋予AlixPayOrder的成员变量
    Order* order = [Order new];
    
    // NOTE: app_id设置
    order.app_id = appID;
    
    // NOTE: 支付接口名称
    
    order.method = @"alipay.trade.app.pay";
    //order.method = [NSString stringWithFormat:@"%@/house/payorder/pay/togetherNotify.html",urlHead];
    
    // NOTE: 参数编码格式
    order.charset = @"utf-8";
    
    // NOTE: 当前时间点
    NSDateFormatter* formatter = [NSDateFormatter new];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    order.timestamp = [formatter stringFromDate:[NSDate date]];
    ////ALI40247
    // NOTE: 支付版本
    order.version = @"1.0";
    
    // NOTE: sign_type 根据商户设置的私钥来决定
    order.sign_type = (rsa2PrivateKey.length > 1)?@"RSA2":@"RSA";
    
    // NOTE: 商品数据
    order.biz_content = [BizContent new];
    order.biz_content.body = @"我是测试数据";
    order.biz_content.subject = @"充值";//订单说明
    order.biz_content.out_trade_no = orderNum;
    //    order.biz_content.out_trade_no = [self generateTradeNO]; //订单ID（由商家自行制定）
    //ALI38173
    order.biz_content.timeout_express = @"30m"; //超时时间设置
    //死的价格
    order.biz_content.total_amount = [NSString stringWithFormat:@"%.2f", [_textPrice.text floatValue]]; //商品价格
    
    
    //将商品信息拼接成字符串
    NSString *orderInfo = [order orderInfoEncoded:NO];
    NSString *orderInfoEncoded = [order orderInfoEncoded:YES];
    
    // NOTE: 获取私钥并将商户信息签名，外部商户的加签过程请务必放在服务端，防止公私钥数据泄露；
    //       需要遵循RSA签名规范，并将签名字符串base64编码和UrlEncode
    NSString *signedString = nil;
    
    RSADataSigner* signer = [[RSADataSigner alloc] initWithPrivateKey:((rsa2PrivateKey.length > 1)?rsa2PrivateKey:rsaPrivateKey)];
    
    if ((rsa2PrivateKey.length > 1)) {
        signedString = [signer signString:orderInfo withRSA2:YES];
    } else {
        signedString = [signer signString:orderInfo withRSA2:NO];
    }
    
    // NOTE: 如果加签成功，则继续执行支付
    if (signedString != nil) {
        //应用注册scheme,在AliSDKDemo-Info.plist定义URL types
        NSString *appScheme = @"alisdkdemo";
        
        // NOTE: 将签名成功字符串格式化为订单字符串,请严格按照该格式
        
        NSString *orderString = [NSString stringWithFormat:@"%@&sign=%@",
                                 orderInfoEncoded, signedString];
        
        //订单信息
        //        orderString = @"测试";
        // NOTE: 调用支付结果开始支付
        [[AlipaySDK defaultService] payOrder:orderString
                                  fromScheme:appScheme callback:^(NSDictionary *
                                                                  resultDic) {
                                      
                                      if ([[resultDic objectForKey:@"resultStatus"] integerValue] == 9000) {
                                          NSLog(@"支付成功");
                                          
                                      }else{
                                          NSLog(@"支付失败");
                                      }
                                      NSLog(@"reslut ============= %@",resultDic);
                                      NSLog(@"memo:%@",[resultDic objectForKey:@"memo"]);
                                  }];
    }
    
}


//生成订单号
- (void)loadData{
    NSString *url = [NSString stringWithFormat:@"%@/App/Shoppingcart/ordernumber",urlHead];
    [[AFHTTPSessionManager manager] POST:url parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        NSLog(@"生产订单号res:%@",responseObject);
        NSString *error = [NSString stringWithFormat:@"%li",[[responseObject objectForKey:@"error"] integerValue]];
        if ([error integerValue] == 200) {
            orderNum = [responseObject objectForKey:@"result"];
        }
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"error:%@",error);
    }];
}


-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [[UIApplication sharedApplication].keyWindow endEditing:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
